package com.holyn.guofang.view.my;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.holyn.guofang.R;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.StatusWo;
import com.holyn.guofang.model.webhttp.wo.UserCardListWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.my.MyContract;
import com.holyn.guofang.presenter.my.MyPresenter;
import com.holyn.guofang.view.BaseActivity;
import com.holyn.guofang.viewcommon.dialog.ValidMethodDialog;
import com.holyn.guofang.viewcommon.popupwindow.PopupSingleSelectFromBottom;
import com.holyn.guofang.viewcommon.radiobutton.DrawableCenterRadioButton;
import com.vondear.rxtools.RxConstUtils;
import com.vondear.rxtools.RxTimeUtils;
import com.vondear.rxtools.view.dialog.RxDialogWheelYearMonthDay;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Holyn on 2017/8/22.
 */

public class MyCardManagerActivity extends BaseActivity implements BaseView, MyContract.CardManagerView{
    private static final int REQUEST_ACTION_POST_USER_CARD_LIST_ACTIVE = 0x0001;
    private static final int REQUEST_ACTION_POST_USER_CARD_LIST_UN_ACTIVE = 0x0002;
    private static final int REQUEST_ACTION_POST_ACTIVE_CARD = 0x0003;

    @BindView(R.id.tv_un_active_card_num)
    TextView tvUnActiveCardNum;
    @BindView(R.id.ll_select_un_active_card)
    LinearLayout llSelectUnActiveCard;
    @BindView(R.id.tv_card_type)
    TextView tvCardType;
    @BindView(R.id.tv_valid_time)
    TextView tvValidTime;
    @BindView(R.id.tv_begin_date)
    TextView tvBeginDate;
    @BindView(R.id.ll_select_begin_date)
    LinearLayout llSelectBeginDate;
    @BindView(R.id.rb_valid_password)
    DrawableCenterRadioButton rbValidPassword;
    @BindView(R.id.rb_valid_code)
    DrawableCenterRadioButton rbValidCode;
    @BindView(R.id.rb_valid_none)
    DrawableCenterRadioButton rbValidNone;
    @BindView(R.id.rg_valid_method)
    RadioGroup rgValidMethod;
    @BindView(R.id.btn_active)
    Button btnActive;
    @BindView(R.id.btn_update_rule)
    Button btnUpdateRule;
    @BindView(R.id.tv_active_card_num)
    TextView tvActiveCardNum;
    @BindView(R.id.tv_active_status)
    TextView tvActiveStatus;
    @BindView(R.id.tv_begin_end_date)
    TextView tvBeginEndDate;
    @BindView(R.id.tv_count)
    TextView tvCount;

    MyContract.Presenter presenter;
    private List<UserCardListWo.DataBean> unActiveCardList = null;
    private UserCardListWo.DataBean activeCard = null;//激活的卡只有一张

    private PopupSingleSelectFromBottom popupSelectUnActiveCard;
    private List<String> unActiveCardCodeList = new ArrayList<>();

    private RxDialogWheelYearMonthDay mRxDialogWheelYearMonthDay;
    Integer cardID;
    String beginDate;
    Integer validMethod = -1;
    String password = "";

    private ValidMethodDialog validMethodDialog = null;

    public SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_my_card_manager;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbar("国方卡管理");

        presenter = new MyPresenter(this);
        presenter.addCardManagerView(this);

        presenter.postUserCardList(REQUEST_ACTION_POST_USER_CARD_LIST_ACTIVE, 1, -1, -1);
        presenter.postUserCardList(REQUEST_ACTION_POST_USER_CARD_LIST_UN_ACTIVE, 2, -1, -1);

        initWheelYearMonthDayDialog();

        initradioGroupView();

    }

    private void initradioGroupView(){
        rgValidMethod.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId){
                    case R.id.rb_valid_password:
                        showValidMethodDialog();
                        break;
                    case R.id.rb_valid_code:
                        validMethod = 1;
                        break;
                    case R.id.rb_valid_none:
                        validMethod = 2;
                        break;
                }
            }
        });
    }

    private void showValidMethodDialog(){
        if (validMethodDialog == null){
            validMethodDialog = new ValidMethodDialog(MyCardManagerActivity.this
                    , new ValidMethodDialog.OnSureClickListener(){
                @Override
                public void onSureClick(String value) {
                    password = value;
                    validMethod = 0;
                }
            }
                    , new ValidMethodDialog.OnCancelClickListener(){
                @Override
                public void onCancelClick() {
                    rgValidMethod.clearCheck();
                    validMethod = -1;
                    password = "";
                }
            });
        }
        validMethodDialog.show();
    }

    @OnClick({R.id.ll_select_un_active_card, R.id.ll_select_begin_date, R.id.btn_active, R.id.btn_update_rule})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_select_un_active_card:
                if (!isHasUnActiveCardList()){
                    toastMsg("没有未启用的卡");
                } else {
                    showPopupSelectUnActiveCard();
                }
                break;
            case R.id.ll_select_begin_date:
                mRxDialogWheelYearMonthDay.show();
                break;
            case R.id.btn_active:
                if (!isHasUnActiveCardList()){
                    toastMsg("当前没有未启用卡");
                    return;
                }
                if (validMethod == -1){
                    toastMsg("请选择扣费规则");
                    return;
                }
                presenter.postActiveCard(REQUEST_ACTION_POST_ACTIVE_CARD, cardID, beginDate, validMethod, password);
                break;
            case R.id.btn_update_rule:
                MyCardManagerUpdateRuleActivity.start(MyCardManagerActivity.this, activeCard.getId(), activeCard.getCardNum());
                break;
        }
    }

    private boolean isHasUnActiveCardList(){
        if (unActiveCardList == null){
            return false;
        } else {
            if (unActiveCardList.size() <= 0){
                return false;
            }
        }
        return true;
    }

    private void showPopupSelectUnActiveCard(){
        if (popupSelectUnActiveCard == null){
            popupSelectUnActiveCard = new PopupSingleSelectFromBottom(MyCardManagerActivity.this, "选择卡号", unActiveCardCodeList);
            popupSelectUnActiveCard.setOnItemClickListener(new PopupSingleSelectFromBottom.OnItemClickListener() {
                @Override
                public void onItemClick(String item, int position) {
                    initUnActiveCardView(position);
                }
            });
        }
        popupSelectUnActiveCard.showPopupWindow();
    }

    private void initUnActiveCardView(int position){
        cardID = unActiveCardList.get(position).getId();
        beginDate = RxTimeUtils.getCurrentDateTime("yyyy-MM-dd");
        tvUnActiveCardNum.setText(unActiveCardList.get(position).getCardNum());
        String cardType = "";
        int cardTypeInt = unActiveCardList.get(position).getCardType();
        if (cardTypeInt == 1){
            cardType = "次卡";
        } else if (cardTypeInt == 2){
            cardType = "期卡";
        }
        cardType = cardType + unActiveCardList.get(position).getName();
        tvCardType.setText(cardType);
        tvValidTime.setText(unActiveCardList.get(position).getEndTime());
        tvBeginDate.setText(beginDate);

    }

    private void initActiveCardView(){
        String cardNum = activeCard.getCardNum();
        if (TextUtils.isEmpty(cardNum)){
            tvActiveCardNum.setText("试用卡-无卡号");
        } else {
            tvActiveCardNum.setText(cardNum);
        }
        boolean activeState = activeCard.isActiveState();
        if (activeState){
            tvActiveStatus.setText("已激活");
        } else {
            tvActiveStatus.setText("未激活");
        }
        String activeTime = activeCard.getActiveTime().substring(0, 10);
        String endTime = activeCard.getEndTime().substring(0, 10);
        tvBeginEndDate.setText("起："+activeTime+"\n止："+endTime);

        int cardTypeInt = activeCard.getCardType();
        if (cardTypeInt == 1){//次卡
            tvCount.setText(activeCard.getRemainCount() + "次");
        } else if (cardTypeInt == 2){//期卡
            String intervalTime = String.valueOf(RxTimeUtils.getIntervalTime(activeTime, endTime, RxConstUtils.TimeUnit.DAY, defaultFormat));
            tvCount.setText(intervalTime + "天");
        }
    }

    @Override
    public void requestStart(Integer requestAction) {
        showLoadingDialog();
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        toastMsg("出现异常");
        closeLoadingDialog();
    }

    @Override
    public void requestComplete(Integer requestAction) {
        closeLoadingDialog();
    }

    @Override
    public void responseSuccess(int requestAction, UserCardListWo userCardListWo) {
        if (userCardListWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            if (requestAction == REQUEST_ACTION_POST_USER_CARD_LIST_ACTIVE){
                List<UserCardListWo.DataBean> activeCardList = userCardListWo.getData();
                if (activeCardList != null){
                    if (activeCardList.size() > 0){
                        activeCard = activeCardList.get(0);
                        initActiveCardView();
                    }
                }
            } else if (requestAction == REQUEST_ACTION_POST_USER_CARD_LIST_UN_ACTIVE){
                unActiveCardList = userCardListWo.getData();
                if (unActiveCardCodeList != null){
                    for (UserCardListWo.DataBean card : unActiveCardList){
                        unActiveCardCodeList.add(card.getCardNum());
                    }
                    if (unActiveCardCodeList.size() > 0){
                        initUnActiveCardView(0);
                    }
                }
            }
        } else {
            toastMsg("获取国方卡信息失败");
        }
    }

    @Override
    public void responseSuccess(int requestAction, StatusWo statusWo) {
        if (requestAction == REQUEST_ACTION_POST_ACTIVE_CARD){
            if (statusWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
                toastMsg("成功启用");
            } else {
                toastMsg("启用失败");
            }
        }
    }

    private void initWheelYearMonthDayDialog() {
        // ------------------------------------------------------------------选择日期开始
        mRxDialogWheelYearMonthDay = new RxDialogWheelYearMonthDay(this, 2000, 2100);
        mRxDialogWheelYearMonthDay.getCheckBox_day().setVisibility(View.GONE);
        mRxDialogWheelYearMonthDay.getYear().setCurrentItem(17);
        mRxDialogWheelYearMonthDay.getTv_sure().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        int year = mRxDialogWheelYearMonthDay.getSelectorYear();
                        String month = mRxDialogWheelYearMonthDay.getSelectorMonth();
                        String day = mRxDialogWheelYearMonthDay.getSelectorDay();
                        String date = year + "-" + month + "-" +day;
                        beginDate = date;
                        tvBeginDate.setText(date);
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        mRxDialogWheelYearMonthDay.getTv_cancle().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        // ------------------------------------------------------------------选择日期结束
    }
}
